<template>
  <el-collapse v-model="expandAll">
    <el-collapse-item
      :title="t('imrStudent.view.modifyTitle')"
      v-if="changeMap && changeMap.size > 0"
      name="1"
    >
      <el-descriptions :column="3" border label-width="80">
        <template v-for="([key, value], index) in changeMapEntries" :key="index">
          <el-descriptions-item :label="t('imrStudent.view.modifyField')" width="220">
            {{ key }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('imrStudent.view.modifyBefore')" width="220">
            {{ value.oldValue }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('imrStudent.view.modifyAfter')" width="220">
            {{ value.newValue }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-collapse-item>
  </el-collapse>
</template>

<script setup lang="ts">
import { ImrStudentVO } from '@/api/core/imrstudent'
import { compareAndFilter } from '@/utils'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime'

const props = defineProps<{
  studentInfo: ImrStudentVO
  studentInfoBackup: ImrStudentVO
}>()

const { t } = useI18n()

interface ChangedValue {
  oldValue: string
  newValue: string
}

const changeMap = ref<Map<string, ChangedValue>>()

const changeMapEntries = computed(() => Array.from((changeMap.value ?? new Map()).entries()))

const expandAll = ref(['1'])
const dateFields = ['birthdate', 'leaveDate']

const init = () => {
  // 记录改动的Map
  changeMap.value = new Map<string, ChangedValue>()

  // 计算出新值有哪些
  const newValue = compareAndFilter(props.studentInfo, props.studentInfoBackup)
  // 计算出旧值有哪些
  const oldValue = compareAndFilter(props.studentInfoBackup, props.studentInfo)

  // 遍历新值
  for (const key in newValue) {
    // 扁平的 没有对象属性
    changeMap.value.set(t(`imrStudent.fields.${key}`), {
      oldValue: dateFields.includes(key) ? formatDate(oldValue[key], 'YYYY-MM-DD') : oldValue[key],
      newValue: dateFields.includes(key) ? formatDate(newValue[key], 'YYYY-MM-DD') : newValue[key]
    })
  }
}

const getModifyField = (): string => {
  return [...Array.from(changeMap.value?.keys() ?? [])].join('、')
}

onMounted(() => {
  init()
})

defineExpose({ getModifyField })
</script>
